/*
 * Created on 2005-7-25
 *
 */
package com.yl.cap.analyst.report.dao.helper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.hibernate.Session;

import com.yl.cap.analyst.exceptions.ErrorFieldFormatException;

/**
 * @author ZhangQi
 *
 */
public class ConReportHelper
{
    public ResultSet getReportData(Session session,String tableName) throws Exception
    {
        ResultSet rs = null;
        Statement stmt = null;
        stmt = session.connection().createStatement();
        String sqlStr = "SELECT * FROM " + tableName;
        rs = stmt.executeQuery(sqlStr);
        ResultSetMetaData rsmd = rs.getMetaData();
        List columnHeads = new ArrayList();
        Map lMap = new HashMap();
        Map dMap = new HashMap();

        for (int i = 1; i <= rsmd.getColumnCount(); ++i)
        {
            String tmpColName = rsmd.getColumnName(i);

            if (tmpColName.equals("Id"))
            {
                continue;
            }
            if (tmpColName.charAt(0) != 'L' && tmpColName.charAt(0) != 'D')
            {
                throw new ErrorFieldFormatException();
            }
            if (tmpColName.charAt(0) == 'L')
            {
                lMap.put(tmpColName, new Integer(i));
            }
            else if (tmpColName.charAt(0) == 'D')
            {
                dMap.put(tmpColName, new Integer(i));
            }
            columnHeads.add(tmpColName);
        }
        rs.close();
        stmt.close();

        int tmpNum = 0;
        String fieldName = null;
        StringBuffer tmpSql = new StringBuffer();
        tmpSql.append(sqlStr);
        tmpSql.append(" group by ");
        List maxList = new ArrayList();

        Object tmpKey = null;

        while (lMap.size() != 0)
        {
            int tmpMAXNum = 0;
            for (int i = 0; i < lMap.size(); i++)
            {
                fieldName = (String) lMap.keySet().toArray()[i];
                tmpNum = Integer.parseInt(fieldName.substring(1, fieldName
                        .length()));
                if (tmpNum > tmpMAXNum)
                {
                    tmpMAXNum = tmpNum;
                    tmpKey = fieldName;
                }
            }
            maxList.add(lMap.get(tmpKey));

            lMap.remove(tmpKey);
            if (lMap.size() != 0)
            {
                tmpSql.append(tmpKey.toString() + ",");
            }
            else
            {
                tmpSql.append(tmpKey.toString());
            }
        }

        stmt = null;
        stmt = session.connection().createStatement();
        return stmt.executeQuery(tmpSql.toString());
    }
}
